package com.guigusuqi.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guigusuqi.app.dto.UserInfoDTO;
import com.guigusuqi.app.entity.DeputyCard;
import com.guigusuqi.app.entity.LoginWxUser;
import com.guigusuqi.app.entity.PO.DeputyCardInfo;
import com.guigusuqi.app.entity.PO.UserCardInfo;
import com.guigusuqi.app.entity.WxUser;
import com.guigusuqi.app.service.WxUserService;
import com.guigusuqi.commonutils.utils.GetTokenByAuthorizationUtils;
import com.guigusuqi.commonutils.utils.HttpClientUtils;
import com.guigusuqi.commonutils.utils.RedisCache;
import com.guigusuqi.commonutils.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@Api(tags = {"wx-微信公众号登录"})
public class WxLoginController
{
    @Resource
    private WxUserService wxUserService;

    @Resource
    private RedisCache redisCache;

    @Value("${oauth.wx.appid}")
    private String appId;

    @Value("${oauth.wx.appsecret}")
    private String appSecret;

    @Value("${oauth.callback.http}")
    private String http;

    @ApiOperation("查看个人信息")
    @GetMapping("selectUserInfo")
    public Result selectUserInfo() throws IOException
    {
        return wxUserService.selectUserInfo();
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyUserInfo")
    public Result modifyUserInfo(@RequestBody(required = true) UserInfoDTO userInfoDTO) throws IOException
    {
        return wxUserService.modifyUserInfo(userInfoDTO);
    }

    @ApiOperation("获取会员卡信息")
    @GetMapping("getUserCardInfo")
    public Result getUserCardInfo() throws IOException
    {
        return wxUserService.getUserCardInfo();
    }
//    @ApiOperation("用户同意授权获取code")
//    @GetMapping("/wxLogin")
//    public Result wxLogin()
//    {
//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +appId+
//                "&redirect_uri=" +http+
//                "&response_type=code" +
//                "&scope=snsapi_base" +
//                "&state=STATE#wechat_redirect";
//        return Result.success().data("url",url);
//    }


//    @GetMapping("/wxLogin")
//    public String wxLogin()
//    {
//        //用户同意授权 获取code
//        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +appId+
//                "&redirect_uri=" +http+
//                "&response_type=code" +
//                "&scope=snsapi_userinfo" +
//                "&state=STATE#wechat_redirect";
//        return "redirect:" + url;
//    }
    /**
     * 第二步：通过code换取网页授权access_token
     * @param code
     * @return
     * @throws IOException
     */
    @ApiOperation("通过code换取openid和授权access_token")
    @GetMapping("/wxcallback/{code}")
    public Result wxcallback(@PathVariable(value = "code",required = true) String code) throws IOException
    {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +appId+
                "&secret=" +appSecret+
                "&code=" +code+
                "&grant_type=authorization_code";
        JSONObject jsonObject = HttpClientUtils.doGet(url);

        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");

        System.out.println("jsonObject:"+jsonObject);
        if(StringUtils.isNotEmpty(openid) && StringUtils.isNotEmpty(access_token))
        {
            return Result.success().data("openid",openid).data("access_token",access_token);
        }else
        {
            return Result.fail().message("认证失败");
        }
    }

    /**
     * 第三步：拉取用户信息(需scope为 snsapi_userinfo),并用返回的userInfoJson关联账号体系
     * @param openid
     * @param access_token
     * @return
     * @throws IOException
     */
   @ApiOperation("通过openid和access_token获取用户信息")
   @GetMapping("/getUserInfo/{openid}/{access_token}")
   public Result getUserInfo(@PathVariable(value = "openid",required = true) String openid,
                             @PathVariable(value = "access_token",required = true) String access_token) throws IOException
   {
       if (StringUtils.isEmpty(openid) || StringUtils.isEmpty(access_token))
       {
           return Result.fail().message("openid或者access_token为空");
       }
       String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +access_token+
               "&openid=" +openid+
               "&lang=zh_CN";
       JSONObject userInfoJson = HttpClientUtils.doGet(url);
       System.out.println("通过openid和access_token获取用户信息");
       if(userInfoJson != null)
       {
           System.out.println("----------------------");
           System.out.println(userInfoJson.toJSONString());
           WxUser wxUser = wxUserService.getUserInfoByOpenId(openid);
           System.out.println("----------------------");
           if(ObjectUtils.isEmpty(wxUser)) //如果数据库没有这个用户就存入
           {
               wxUser = new WxUser();
               wxUser.setOpenid((String) userInfoJson.get("openid"));
               wxUser.setNickname((String) userInfoJson.get("nickname"));
               wxUser.setImage((String) userInfoJson.get("headimgurl"));
               wxUser.setSex((Integer) userInfoJson.get("sex"));
               wxUserService.save(wxUser);
           }else //如果数据库有这个用户 就通过openid更新信息
           {
               System.out.println("数据库有这个用户");
               wxUser.setNickname((String) userInfoJson.get("nickname"));
               wxUser.setImage((String) userInfoJson.get("headimgurl"));
               wxUser.setSex((Integer) userInfoJson.get("sex"));

               LambdaQueryWrapper<WxUser> queryWrapper = new LambdaQueryWrapper<>();
               queryWrapper.eq(WxUser::getOpenid,openid);

               wxUserService.update(wxUser,queryWrapper);
           }
           /*将用户信息存入数据库之后 就进行登录,通过openid获取token返回给前端*/
           String token = wxUserService.wxLogin(openid);

           return Result.success().data("userInfo",wxUser).data("token",token);
       }else
       {
           return Result.fail().message("获取用户信息失败！");
       }
   }

   @ApiOperation("通过openid进行微信登录")
   @GetMapping("wxLogin/{openid}")
   public Result wxLogin(@PathVariable(value = "openid",required = true) String openid)
   {
        String token =  wxUserService.wxLogin(openid);

        WxUser wxUser =  wxUserService.getUserInfoByOpenId(openid);
        if(StringUtils.isEmpty(token))
        {
            return Result.fail().message("openid有误");
        }

       return Result.success().data("userInfo",wxUser).data("token",token);
   }

   @ApiOperation("退出登录")
   @GetMapping("logOut")
   public Result logOut() throws IOException
   {
       String token = GetTokenByAuthorizationUtils.getToken();
       boolean b = redisCache.deleteObject("TOKEN_" + token);
       if(b)
       {
           return Result.success().message("退出成功");
       }else
       {
           return Result.fail().message("退出失败");
       }
   }
}
